package com.xxtx.trade.sysUser.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.xxtx.trade.common.exception.BusinessException;
import com.xxtx.trade.common.util.IdCreateUtil;
import com.xxtx.trade.common.util.PhoneUtils;
import com.xxtx.trade.common.util.StringUtil;
import com.xxtx.trade.common.util.cache.CacheManager;
import com.xxtx.trade.common.util.model.PageInfo;
import com.xxtx.trade.common.util.model.Result;
import com.xxtx.trade.common.util.security.MD5;
import com.xxtx.trade.common.utils.IdCardUtils;
import com.xxtx.trade.common.utils.ResponseVo;
import com.xxtx.trade.common.utils.SendSMSUtil;
import com.xxtx.trade.sysUser.bean.SysUserPhone;
import com.xxtx.trade.sysUser.bean.SysUserPhoneConstant;
import com.xxtx.trade.sysUser.dto.BindPhoneConstant;
import com.xxtx.trade.sysUser.dto.SysUserPhoneDto;
import com.xxtx.trade.sysUser.mapper.SysUserPhoneMapper;
import com.xxtx.trade.sysUser.service.SysUserPhoneService;
import com.xxtx.trade.sysUser.vo.SysUserPhoneVo;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;
import java.util.*;

@Service

public class SysUserPhoneServiceImpl implements SysUserPhoneService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysUserPhoneServiceImpl.class);


    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private SysUserPhoneMapper sysUserPhoneMapper;
    /**
     * 绑定用户的手机号
     *
     * @param sysUserPhone
     * @return
     */
    @Override
    public Result bindSysUserPhone(SysUserPhoneDto sysUserPhone) throws NoSuchAlgorithmException {
        if (sysUserPhone.getIccid()!=null&&sysUserPhone.getIccid().length()<18){
            sysUserPhone.setIccid(sysUserPhoneMapper.selecticcidByIntoNo(sysUserPhone.getIccid()));
        }

        LOGGER.info("手机绑定的入参{}", sysUserPhone);
        Result<Object> result = new Result<>();
        try {
            if (StringUtil.isEmpty(sysUserPhone.getName())) {
                result.setMessage("请输入真实名称");
                result.setCode(400);
                return result;
            }
            if (!PhoneUtils.isValidChinesePhone(sysUserPhone.getUserPhone())) {
                result.setMessage("请输入合法的手机号");
                result.setCode(400);
                return result;
            }
            if (sysUserPhone.getSmsCode() == 0) {
                result.setMessage("请输入验证码");
                result.setCode(400);
                return result;
            }
            //查询是否有这张卡
            String simInfo =  sysUserPhoneMapper.selectSimInfoByIccid(sysUserPhone.getIccid());
            if (StringUtils.isEmpty(simInfo)) {
                result.setCode(400);
                result.setMessage("请输入有效的iccid号");
                return result;
            }

            Integer anInt = (Integer) cacheManager.get(SysUserPhoneConstant.REDIS_INDEX + sysUserPhone.getUserPhone());
            if (anInt == null) {
                result.setCode(400);
                result.setMessage("验证码失效请重新获取");
                return result;
            }
            if (!anInt.equals(sysUserPhone.getSmsCode())) {
                result.setMessage("请输入正确的验证码");
                result.setCode(400);
                return result;
            }

            Object o = cacheManager.get(BindPhoneConstant.REDIS_BIND + sysUserPhone.getIccid());
            if (o!=null&&Integer.valueOf(String.valueOf(0))>2){
                return Result.error("当前实名认证错误超过三次");
            }
            if (true) {
                //查询当前身份信息是否已经实名过了
                SysUserPhoneDto sysUserPhoneDto = new SysUserPhoneDto();
                //查询当前手机号是否已实名过了
                sysUserPhoneDto.setUserPhone(sysUserPhone.getUserPhone());
                sysUserPhoneDto.setName(sysUserPhone.getName());
                sysUserPhoneDto.setIdcard(sysUserPhone.getIdcard());
                List<SysUserPhone> list = sysUserPhoneMapper.selectQueryList(sysUserPhoneDto);
                if(list!=null && list.size() >0){ //已实名
                    sysUserPhone.setIdcardRemark(list.get(0).getIdcardRemark());
                }else {

                    //实名验证
                        ResponseVo<Map<String, Object>> rv = IdCardUtils.checkIdCard(sysUserPhone.getName(), sysUserPhone.getUserPhone(), sysUserPhone.getIdcard());
                        LOGGER.info("当前实名信息为：{}", JSONObject.toJSONString(rv));
                        if (rv != null) {
                            if (rv.isSuccess()) {
                                if (rv.getCode() == 200) {
                                    Object res = rv.getData().get("result");
                                    if (Integer.valueOf(res + "").equals(0)) {
                                        //一致
                                        cacheManager.incrBy(BindPhoneConstant.REDIS_BIND+sysUserPhone.getIccid(),1);
                                        sysUserPhone.setIdcard(sysUserPhone.getIdcard());
                                        sysUserPhone.setIdcardRemark(JSONObject.toJSONString(rv.getData()));
                                    }else {
                                        //身份证号与手机号不一致
                                        cacheManager.incrBy(BindPhoneConstant.REDIS_BIND+sysUserPhone.getIccid(),1);
                                        return Result.error("当前姓名，身份证号，手机号与本人真实信息不一致！");
                                    }
                                } else {
                                    cacheManager.incrBy(BindPhoneConstant.REDIS_BIND+sysUserPhone.getIccid(),1);
                                    return Result.error( rv.getMsg());
                                }
                            } else {
                                cacheManager.incrBy(BindPhoneConstant.REDIS_BIND+sysUserPhone.getIccid(),1);
                                return Result.error( rv.getMsg());
                            }
                        } else {
                            cacheManager.incrBy(BindPhoneConstant.REDIS_BIND+sysUserPhone.getIccid(),1);
                            throw new BusinessException(400,"网络繁忙,请稍候重试");
                        }


                   // }
                }
            }

            //查询当前手机号有没有被绑定
            SysUserPhoneVo sysUserPhoneVo = sysUserPhoneMapper.selectByIccid(sysUserPhone);
            if (sysUserPhoneVo != null) {
                result.setCode(400);
                result.setMessage("绑定失败！当前卡已被绑定");
                return result;
            }

            List<SysUserPhoneVo> phoneVos = sysUserPhoneMapper.selectBindList(sysUserPhone);
            if (phoneVos.size()>3){
                return Result.error("一张身份证信息只能认证三次！");
            }
            //存入数据库
            SysUserPhone phone = new SysUserPhone();
            phone.setId(IdCreateUtil.getId());
            phone.setCreateTime(new Date());
            phone.setUserPhone(sysUserPhone.getUserPhone());
            phone.setIccid(sysUserPhone.getIccid());
            phone.setName(sysUserPhone.getName());
            phone.setIdcard(sysUserPhone.getIdcard());
            phone.setIdcardRemark(sysUserPhone.getIdcardRemark());

            //查询是否更改默认
            List<String> defaultSimByPhone = sysUserPhoneMapper.selectByDefaultSimByPhone(sysUserPhone);
            if (defaultSimByPhone == null || defaultSimByPhone.size() == 0) {
                phone.setSimDefault(1);
                sysUserPhoneMapper.insertSelective(phone);
            } else {
                sysUserPhoneMapper.insert(phone);
            }

//            if(sysUserPhoneMapper.selectAccountByMobile(sysUserPhone.getUserPhone()) <= 0) {
//                Map<String, Object> params = new HashMap<>();
//                params.put("mobile", sysUserPhone.getUserPhone());
//                params.put("payPass", MD5.MD5_32bit(sysUserPhone.getPayPass()));
//                params.put("amount", 0);
//                params.put("createTime", new Date());
//                int count = sysUserPhoneMapper.insertUserAccount(params);
//                LOGGER.info("mobile:{} 开户:{}", sysUserPhone.getIccid(), count);
//            }
        } catch (Exception e) {
            LOGGER.warn("绑定用户手机号异常，异常信息为{}" + sysUserPhone);
            result.setMessage("绑定失败，请稍后再试");
            result.setCode(400);
        }
        return result;
    }

    /**
     * 获取短信验证码
     *
     * @param sysUserPhone
     * @return
     */
    @Override
    public Result getSmsCode(SysUserPhoneDto sysUserPhone) {
        LOGGER.info("短信验证码的入参{}", sysUserPhone);
        Result<Object> result = new Result<>();
        try {
            if (!PhoneUtils.isValidChinesePhone(sysUserPhone.getUserPhone())) {
                result.setMessage("请输入合法的手机号");
                result.setCode(400);
                return result;
            }
            //判断是否重复申请
            Integer anInt = (Integer) cacheManager.get(SysUserPhoneConstant.REDIS_INDEX + sysUserPhone.getUserPhone());
            if (anInt != null) {
                result.setCode(400);
                result.setMessage("您之前获取的验证码还未过期，请忽重复获取。");
                return result;
            }
            //获取code
            int smsCode = PhoneUtils.getSMSCode();
            //查看当前短信配置
            boolean sms= SendSMSUtil.sendSMS(sysUserPhone.getUserPhone(), String.valueOf(smsCode));

            if (!sms) {
                result.setCode(400);
                result.setMessage("发送失败，请稍后再试");
                return result;
            }
            //存入redis 300s失效
            cacheManager.set(SysUserPhoneConstant.REDIS_INDEX + sysUserPhone.getUserPhone(), smsCode, 300);
            //设置55秒内不准重复申请
            cacheManager.set(SysUserPhoneConstant.SMS_CODE_TIME + sysUserPhone.getUserPhone(), smsCode, 55);
        } catch (Exception e) {
            LOGGER.warn("获取用户绑定手机验证码错误，异常信息为{}" + sysUserPhone);
            result.setMessage("系统繁忙，请稍后再试");
            result.setCode(400);
        }
        return result;
    }

    /**
     * 查看绑定手机号的列表
     *
     * @param sysUserPhoneDto
     * @return
     */
    @Override
    public Result iccidList(SysUserPhoneDto sysUserPhoneDto) {
        LOGGER.info("手机绑定列表的入参{}", sysUserPhoneDto);
        Result<Object> result = new Result<>();
        try {
            List<SysUserPhoneVo> noticeList = sysUserPhoneMapper.selectBindList(sysUserPhoneDto);
            if (noticeList == null || noticeList.size() == 0) {
                result.setMessage("当前手机号未绑定流量卡");
                result.setCode(400);
                return result;
            }

            result.setData(noticeList);
        } catch (Exception e) {
            result.setMessage("系统繁忙，请稍后再试");
            result.setCode(400);
        }

        return result;
    }

    /**
     * 解绑卡片
     *
     * @param sysUserPhoneDto
     * @return
     */
    @Override
    public Result updateBindPhone(SysUserPhoneDto sysUserPhoneDto) {
        LOGGER.info("更改手机号的入参{}", sysUserPhoneDto);
        Result<Object> result = new Result<>();
        try {
            //将删除的卡数据添加到新的表
            sysUserPhoneMapper.insertDelete(sysUserPhoneDto);
            sysUserPhoneMapper.deleteByIccid(sysUserPhoneDto.getIccid());
            List<SysUserPhoneVo> list = sysUserPhoneMapper.selectBindList(sysUserPhoneDto);
            int a = 0;
            if (list != null && list.size() > 0) {
                //判断删除的是不是默认的
                for (SysUserPhoneVo phoneVo : list) {
                    if (phoneVo.getSimDefault() == 1) {
                        a++;
                    }
                    sysUserPhoneDto.setDefaultIccid(phoneVo.getIccid());
                }
            }
            if (a == 0) {
                sysUserPhoneMapper.updatesimDefault(sysUserPhoneDto);
            }
            result.setData(list);
        } catch (Exception e) {
            LOGGER.warn("更改绑定用户手机号异常，异常信息为{}" + sysUserPhoneDto);
            result.setMessage("更改失败，请稍后再试");
            result.setCode(400);
        }
        return result;
    }

    /**
     * 查看默认的手机号
     *
     * @param dto
     * @return
     */
    @Override
    public Result<Object> selectByDefaultSimByPhone(SysUserPhoneDto dto) {
        Result<Object> result = new Result<>();
        String iccid = null;
        try {
            List<String> list = sysUserPhoneMapper.selectByDefaultSimByPhone(dto);
            if (list != null && list.size() > 0) {
                iccid = list.get(0);
            }
            result.setData(iccid);
        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("操作频繁，请稍后再试");
        }
        return result;
    }

    /**
     * 设为默认
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result<Object> updateyDefaultSimByPhone(SysUserPhoneDto dto) {
        Result<Object> result = new Result<>();
        int i = sysUserPhoneMapper.updateByDefaultSimByPhone(dto);
        int i1 = sysUserPhoneMapper.updatesimDefault(dto);
        //让事务回滚
        if (i == 0 || i1 == 0) {
            throw new RuntimeException();
        }
        return result;
    }

    /**
     * 查看所有绑定过得手机列表
     */
    @Override
    public Result selectQueryList(SysUserPhoneDto dto) {
        Result<Object> result = new Result<>();
        try {
            Page page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "create_time DESC");
            List<SysUserPhone> list = sysUserPhoneMapper.selectQueryList(dto);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(list);
            result.setData(pageInfo);
        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("查看列表失败");
        }
        return result;
    }

    /**
     * 根据查询条件，查询帐户信息
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, String> selectAccountBy(Map<String, String> params) {
        return sysUserPhoneMapper.selectAccountBy(params);
    }

    /**
     * 设置支付密码
     *
     * @param params
     * @return
     */
    @Override
    public int setPayPass(Map<String, Object> params) throws NoSuchAlgorithmException {
        params.put("payPass", MD5.md5(params.get("payPass") + ""));
        return sysUserPhoneMapper.setPayPass(params);
    }

    @Override
    public Map<String, Object> selectMobileByIccid(String iccid) {
        return sysUserPhoneMapper.selectMobileByIccid(iccid);
    }


    @Override
    public Result selectQueryorderList(SysUserPhoneDto dto) {
        Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "create_time DESC");
        List<Map<String,Object>> list= sysUserPhoneMapper.selectorderList(dto);
        for (Map<String, Object> map : list) {
            String iccid = (String) map.get("iccid");
            Integer anInt = cacheManager.getInt(BindPhoneConstant.REDIS_BIND + iccid);
            map.put("allAuth",anInt);
        }
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNo(page.getPageNum());
        pageInfo.setPerPageNum(page.getPageSize());
        pageInfo.setTotalNum(page.getTotal());
        pageInfo.setResultList(list);
        return Result.success(pageInfo);

    }

    @Override
    public Result selectupdateOrderstate(SysUserPhoneDto dto) {
        if (dto.getIccid()==null){
            return Result.error("iccid为空");
        }
       cacheManager.set(BindPhoneConstant.REDIS_BIND+dto.getIccid(),0);
        return Result.success();
    }
}
